<!--
 * @Description: 
 * @Author: ldx
 * @Date: 2023-03-02 21:05:41
 * @LastEditors: ldx
 * @LastEditTime: 2023-03-13 08:31:57
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script id="vertex" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    void main(){
      // 顶点位置
      gl_Position = a_Position;
      // 顶点大小
      gl_PointSize = 100.0;
    }
  </script>
  <script id="fragment" type="x-shader/x-fragment">
    void main(){
      // 片元颜色
      gl_FragColor = vec4(1,0,0,1);
    }
  </script>
  <canvas id="canvas"></canvas>
  <script type="module">
    import { initProgram } from '../jsm/utils.js'
    const canvas = document.querySelector('#canvas')
    // 设置canvas容器的宽高
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 获取webgl上下文
    const gl = canvas.getContext('webgl');
    // 声明将来用来清空绘图区的颜色。分别对应r,g,b,a
    gl.clearColor(0, 0, 0, 1)
    // 使用之前声明的颜色，清空绘图区
    gl.clear(gl.COLOR_BUFFER_BIT)

    // 初始化程序对象
    initProgram(gl)
    const points = [{
      x:0.5,
      y:0
    }]
    // 获取attribute变量并修改
    const a_Position = gl.getAttribLocation(gl.program, 'a_Position')
    render()
    // 获取canvas容器的一半宽高
    const halfW = canvas.clientWidth / 2
    const halfH = canvas.clientHeight / 2
    
    canvas.addEventListener('click', ({ clientX, clientY }) => {
      // 计算webgl坐标系下的鼠标位置
      const x = (clientX - halfW) / halfW
      const y = -(clientY - halfH) / halfH
      points.push({x,y})
      render()
    })
    // 渲染
    function render() {
      gl.clear(gl.COLOR_BUFFER_BIT)
      points.forEach(({ x, y }) => {
        gl.vertexAttrib2f(a_Position, x, y)
        gl.drawArrays(gl.POINT, 0, 1)
      })
    }


  </script>
</body>

</html>